import { currentUser, userService, USER_TYPES } from './userService.js'

// 智能Agent代理服务
class IntelligentAgent {
  constructor() {
    this.agentConfig = {
      // 用户画像分析
      userProfile: {
        industry: 'ecommerce', // 行业
        companySize: 'medium', // 企业规模
        businessType: 'import_export', // 业务类型
        interests: ['tax_policy', 'trade_policy'], // 关注的政策类型
        location: '华东地区', // 地区
        riskLevel: 'medium' // 风险偏好
      },
      
      // 推送偏好设置
      pushPreferences: {
        frequency: 'realtime', // daily, weekly, realtime
        priority: 'high', // high, medium, low
        channels: ['notification', 'digital_human', 'voice'], // 推送渠道
        timeRange: { start: '09:00', end: '18:00' }, // 推送时间范围
        keywords: ['税收', '优惠', '补贴', '跨境'], // 关键词过滤
        enableSmartAnalysis: true, // 启用智能分析
        autoAnnouncement: true // 自动播报
      },
      
      // 智能分析配置
      analysisConfig: {
        policyMatching: true, // 政策匹配
        riskAssessment: true, // 风险评估
        opportunityDetection: true, // 机会发现
        trendPrediction: true, // 趋势预测
        competitorAnalysis: false, // 竞争对手分析
        marketInsights: true // 市场洞察
      }
    }
    
    this.eventListeners = new Map()
    this.pushQueue = []
    this.announcementQueue = []
    this.isActive = false
    this.lastUpdateTime = Date.now()
    this.statistics = {
      totalPushes: 0,
      highPriorityPushes: 0,
      announcements: 0,
      policyMatches: 0,
      userEngagement: 0
    }
    
    this.initializeAgent()
  }

  // 根据用户类型初始化配置
  initializeUserTypeConfig() {
    const userType = currentUser.type || USER_TYPES.INDIVIDUAL
    const userConfig = userService.getUserTypeConfig(userType)
    
    // 根据用户类型调整Agent配置
    switch (userType) {
      case USER_TYPES.ENTERPRISE:
        this.agentConfig.userProfile = {
          ...this.agentConfig.userProfile,
          industry: currentUser.profile?.industry || 'manufacturing',
          companySize: currentUser.profile?.scale || 'large',
          businessType: 'enterprise_operations',
          interests: ['compliance_monitoring', 'risk_assessment', 'tax_policy', 'trade_policy'],
          location: currentUser.profile?.location || '全国',
          riskLevel: 'high'
        }
        this.agentConfig.pushPreferences.frequency = 'realtime'
        this.agentConfig.pushPreferences.priority = 'high'
        this.agentConfig.analysisConfig.competitorAnalysis = true
        break
        
      case USER_TYPES.GOVERNMENT:
        this.agentConfig.userProfile = {
          ...this.agentConfig.userProfile,
          industry: 'government',
          companySize: 'large',
          businessType: 'policy_administration',
          interests: ['policy_impact_analysis', 'regulatory_compliance', 'public_feedback'],
          location: currentUser.profile?.jurisdiction || '全国',
          riskLevel: 'low'
        }
        this.agentConfig.pushPreferences.frequency = 'immediate'
        this.agentConfig.pushPreferences.priority = 'high'
        this.agentConfig.analysisConfig.policyMatching = false
        this.agentConfig.analysisConfig.marketInsights = false
        break
        
      case USER_TYPES.ACADEMIC:
        this.agentConfig.userProfile = {
          ...this.agentConfig.userProfile,
          industry: 'research',
          companySize: 'medium',
          businessType: 'academic_research',
          interests: ['research_data', 'trend_analysis', 'policy_impact'],
          location: currentUser.profile?.location || '全国',
          riskLevel: 'low'
        }
        this.agentConfig.pushPreferences.frequency = 'weekly'
        this.agentConfig.pushPreferences.priority = 'medium'
        this.agentConfig.analysisConfig.trendPrediction = true
        this.agentConfig.analysisConfig.competitorAnalysis = false
        break
        
      case USER_TYPES.INDIVIDUAL:
      default:
        this.agentConfig.userProfile = {
          ...this.agentConfig.userProfile,
          industry: currentUser.profile?.occupation || 'ecommerce',
          companySize: 'small',
          businessType: 'personal_business',
          interests: ['tax_policy', 'personal_recommendations'],
          location: currentUser.profile?.location || '华东地区',
          riskLevel: 'medium'
        }
        this.agentConfig.pushPreferences.frequency = 'daily'
        this.agentConfig.pushPreferences.priority = 'medium'
        this.agentConfig.analysisConfig.competitorAnalysis = false
        this.agentConfig.analysisConfig.opportunityDetection = true
        break
    }
  }

  // 获取用户类型特定的服务
  getUserTypeServices() {
    const userType = currentUser.type || USER_TYPES.INDIVIDUAL
    return userService.getAgentServices()
  }

  // 检查用户是否有特定服务权限
  hasServiceAccess(serviceName) {
    const services = this.getUserTypeServices()
    return services.includes(serviceName)
  }
  
  // 初始化智能代理（公共接口）
  async initialize() {
    return await this.initializeAgent()
  }

  // 初始化智能代理
  async initializeAgent() {
    console.log('🤖 智能Agent代理启动中...')
    
    // 根据用户类型初始化配置
    this.initializeUserTypeConfig()
    
    // 加载用户配置
    this.loadUserProfile()
    
    // 启动实时监控
    this.startRealTimeMonitoring()
    
    // 启动定时任务
    this.startScheduledTasks()
    
    this.isActive = true
    console.log('✅ 智能Agent代理已启动')
    
    // 发送欢迎消息
    this.sendWelcomeMessage()
    
    // 触发初始推荐
    setTimeout(() => {
      this.performInitialAnalysis()
    }, 2000)
  }
  
  // 加载用户画像
  loadUserProfile() {
    const saved = localStorage.getItem('agent_user_profile')
    if (saved) {
      this.agentConfig.userProfile = { ...this.agentConfig.userProfile, ...JSON.parse(saved) }
    }
    
    const savedPrefs = localStorage.getItem('agent_push_preferences')
    if (savedPrefs) {
      this.agentConfig.pushPreferences = { ...this.agentConfig.pushPreferences, ...JSON.parse(savedPrefs) }
    }
  }
  
  // 保存用户画像
  saveUserProfile() {
    localStorage.setItem('agent_user_profile', JSON.stringify(this.agentConfig.userProfile))
    localStorage.setItem('agent_push_preferences', JSON.stringify(this.agentConfig.pushPreferences))
  }
  
  // 更新用户画像
  updateUserProfile(profileData) {
    this.agentConfig.userProfile = { ...this.agentConfig.userProfile, ...profileData }
    this.saveUserProfile()
    
    // 重新分析和推荐
    this.reanalyzeAndRecommend()
  }
  
  // 更新推送偏好
  updatePushPreferences(preferences) {
    this.agentConfig.pushPreferences = { ...this.agentConfig.pushPreferences, ...preferences }
    this.saveUserProfile()
    
    // 重新配置推送策略
    this.reconfigurePushStrategy()
  }
  
  // 重新配置推送策略
  reconfigurePushStrategy() {
    console.log('📝 重新配置推送策略...')
    
    // 根据用户偏好调整推送频率和类型
    this.emitEvent('pushStrategyUpdated', {
      preferences: this.agentConfig.pushPreferences,
      timestamp: Date.now()
    })
  }
  
  // 开始实时监控
  startRealTimeMonitoring() {
    // 监控政策更新
    setInterval(() => {
      this.checkPolicyUpdates()
    }, 30000) // 30秒检查一次
    
    // 监控市场变化
    setInterval(() => {
      this.checkMarketChanges()
    }, 60000) // 1分钟检查一次
    
    // 监控风险变化
    setInterval(() => {
      this.checkRiskChanges()
    }, 120000) // 2分钟检查一次
    
    // 监控用户行为模式
    setInterval(() => {
      this.analyzeUserBehavior()
    }, 300000) // 5分钟分析一次
  }
  
  // 开始定时任务
  startScheduledTasks() {
    // 每日摘要推送
    this.scheduleDailyDigest()
    
    // 周报生成
    this.scheduleWeeklyReport()
    
    // 重要提醒
    this.scheduleImportantReminders()
    
    // 用户画像更新
    this.scheduleProfileUpdate()
  }
  
  // 执行初始分析
  async performInitialAnalysis() {
    console.log('🔍 执行初始政策分析...')
    
    const recommendations = await this.generateCustomizedRecommendations()
    
    if (recommendations.length > 0) {
      // 推送欢迎推荐
      this.queueHighPriorityPush({
        type: 'welcome_recommendations',
        title: '智能推荐已准备就绪',
        content: `基于您的企业画像，我们为您匹配了${recommendations.length}项相关政策`,
        data: recommendations.slice(0, 5),
        urgency: 'medium',
        enableDigitalHuman: true
      })
    }
  }
  
  // 分析用户行为模式
  analyzeUserBehavior() {
    // 简化的用户行为分析
    const currentHour = new Date().getHours()
    const isWorkingHours = currentHour >= 9 && currentHour <= 18
    
    if (isWorkingHours && Math.random() > 0.7) {
      this.statistics.userEngagement += 1
      
      // 根据用户活跃度调整推送策略
      if (this.statistics.userEngagement > 10) {
        this.checkForHighPriorityUpdates()
      }
    }
  }
  
  // 检查高优先级更新
  async checkForHighPriorityUpdates() {
    const urgentPolicies = await this.getUrgentPolicies()
    
    for (const policy of urgentPolicies) {
      const relevanceScore = this.calculatePolicyRelevance(policy)
      
      if (relevanceScore > 0.8) {
        this.queueHighPriorityPush({
          type: 'urgent_policy',
          title: '紧急政策通知',
          content: policy.title,
          data: policy,
          urgency: 'high',
          enableDigitalHuman: true,
          autoAnnounce: true
        })
      }
    }
  }
  
  // 获取紧急政策
  async getUrgentPolicies() {
    // 模拟紧急政策获取
    const urgentPolicies = [
      {
        id: 'urgent_' + Date.now(),
        title: '跨境电商新税收政策即将生效',
        type: 'tax_policy',
        region: '全国',
        impact: 'high',
        industry: ['ecommerce', 'import_export'],
        effectDate: new Date(Date.now() + 3 * 24 * 60 * 60 * 1000),
        summary: '新的跨境电商税收政策将于3天后生效，可能影响您的业务成本结构...',
        urgency: 'high',
        deadline: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000)
      }
    ]
    
    return urgentPolicies.filter(() => Math.random() > 0.8) // 20%概率返回紧急政策
  }
  
  // 检查政策更新
  async checkPolicyUpdates() {
    try {
      const updates = await this.fetchLatestPolicies()
      
      if (updates.length > 0) {
        for (const update of updates) {
          const relevanceScore = this.calculatePolicyRelevance(update)
          
          this.statistics.policyMatches += 1
          
          if (relevanceScore > 0.7) {
            this.queueHighPriorityPush({
              type: 'policy_update',
              title: '重要政策更新',
              content: update.title,
              data: update,
              urgency: relevanceScore > 0.85 ? 'high' : 'medium',
              relevance: relevanceScore,
              enableDigitalHuman: relevanceScore > 0.8
            })
          }
        }
      }
    } catch (error) {
      console.error('政策更新检查失败:', error)
    }
  }
  
  // 获取最新政策
  async fetchLatestPolicies() {
    // 模拟API调用，返回更丰富的政策数据
    const policyPool = [
      {
        id: 'policy_' + Date.now(),
        title: '跨境电商税收优惠政策调整',
        type: 'tax_policy',
        region: '全国',
        impact: 'high',
        industry: ['ecommerce', 'import_export'],
        effectDate: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000),
        summary: '针对跨境电商企业的税收优惠政策进行重大调整，预计影响进出口业务成本...',
        benefit: '税负减免20-35%',
        requirements: ['年营业额500万以上', '跨境业务占比50%以上'],
        deadline: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000)
      },
      {
        id: 'policy_' + (Date.now() + 1),
        title: '制造业企业数字化转型补贴政策',
        type: 'subsidy_policy',
        region: '华东地区',
        impact: 'medium',
        industry: ['manufacturing'],
        effectDate: new Date(Date.now() + 14 * 24 * 60 * 60 * 1000),
        summary: '支持制造业企业进行数字化转型，最高补贴500万元...',
        benefit: '最高补贴500万元',
        requirements: ['制造业企业', '数字化转型项目', '符合环保要求'],
        deadline: new Date(Date.now() + 60 * 24 * 60 * 60 * 1000)
      },
      {
        id: 'policy_' + (Date.now() + 2),
        title: '新能源企业投资优惠政策',
        type: 'investment_policy',
        region: '全国',
        impact: 'high',
        industry: ['energy', 'manufacturing'],
        effectDate: new Date(Date.now() + 21 * 24 * 60 * 60 * 1000),
        summary: '为促进新能源产业发展，提供税收减免和投资补贴...',
        benefit: '投资额15%税收抵免',
        requirements: ['新能源相关业务', '投资额1000万以上'],
        deadline: new Date(Date.now() + 90 * 24 * 60 * 60 * 1000)
      }
    ]
    
    // 模拟随机返回1-2个政策
    const numPolicies = Math.floor(Math.random() * 2) + 1
    return policyPool.slice(0, numPolicies).filter(() => Math.random() > 0.3)
  }
  
  // 计算政策相关性
  calculatePolicyRelevance(policy) {
    const profile = this.agentConfig.userProfile
    let score = 0
    
    // 行业匹配
    if (policy.industry && policy.industry.includes(profile.industry)) {
      score += 0.4
    }
    
    // 地区匹配
    if (policy.region === '全国' || policy.region === profile.location) {
      score += 0.3
    }
    
    // 关注点匹配
    if (profile.interests.some(interest => policy.type.includes(interest))) {
      score += 0.2
    }
    
    // 关键词匹配
    const keywords = this.agentConfig.pushPreferences.keywords
    const policyText = `${policy.title} ${policy.summary}`.toLowerCase()
    const keywordMatches = keywords.filter(keyword => 
      policyText.includes(keyword.toLowerCase())
    ).length
    
    if (keywordMatches > 0) {
      score += Math.min(keywordMatches * 0.05, 0.1)
    }
    
    return Math.min(score, 1.0)
  }
  
  // 队列高优先级推送
  queueHighPriorityPush(pushData) {
    const pushItem = { 
      ...pushData, 
      id: 'push_' + Date.now(),
      timestamp: Date.now(), 
      priority: 'high',
      processed: false
    }
    
    this.pushQueue.unshift(pushItem)
    this.statistics.highPriorityPushes += 1
    
    this.processPushQueue()
  }
  
  // 队列普通推送
  queueNormalPush(pushData) {
    const pushItem = { 
      ...pushData, 
      id: 'push_' + Date.now(),
      timestamp: Date.now(), 
      priority: 'normal',
      processed: false
    }
    
    this.pushQueue.push(pushItem)
    this.processPushQueue()
  }
  
  // 处理推送队列
  processPushQueue() {
    if (this.pushQueue.length === 0) return
    
    // 按优先级和时间排序
    this.pushQueue.sort((a, b) => {
      if (a.priority === 'high' && b.priority !== 'high') return -1
      if (a.priority !== 'high' && b.priority === 'high') return 1
      return b.timestamp - a.timestamp
    })
    
    // 处理未处理的推送
    const unprocessedPushes = this.pushQueue.filter(push => !push.processed)
    
    for (const push of unprocessedPushes) {
      if (this.shouldExecutePush(push)) {
        this.executePush(push)
        push.processed = true
      }
    }
    
    // 清理已处理的推送（保留最近100条）
    this.pushQueue = this.pushQueue.filter(push => !push.processed).slice(0, 100)
  }
  
  // 判断是否应该执行推送
  shouldExecutePush(pushData) {
    // 检查推送时间范围
    if (!this.isWithinPushTimeRange()) {
      if (pushData.urgency !== 'high') {
        return false
      }
    }
    
    // 检查推送频率限制
    const recentPushes = this.pushQueue.filter(push => 
      push.processed && (Date.now() - push.timestamp) < 60000 // 1分钟内
    )
    
    if (recentPushes.length >= 3 && pushData.urgency !== 'high') {
      return false
    }
    
    return true
  }
  
  // 执行推送
  executePush(pushData) {
    console.log('📤 执行推送:', pushData.title)
    
    this.statistics.totalPushes += 1
    
    // 发送到通知中心
    this.emitEvent('newNotification', {
      ...pushData,
      id: pushData.id || 'notification_' + Date.now(),
      timestamp: Date.now()
    })
    
    // 如果启用数字人播报
    if (pushData.enableDigitalHuman && this.agentConfig.pushPreferences.autoAnnouncement) {
      this.triggerDigitalHumanAnnouncement(pushData)
    }
    
    // 如果需要自动播报
    if (pushData.autoAnnounce) {
      setTimeout(() => {
        this.triggerDigitalHumanAnnouncement(pushData)
      }, 2000)
    }
  }
  
  // 检查是否在推送时间范围内
  isWithinPushTimeRange() {
    const now = new Date()
    const currentTime = now.getHours() * 60 + now.getMinutes()
    const { start, end } = this.agentConfig.pushPreferences.timeRange
    
    const startMinutes = parseInt(start.split(':')[0]) * 60 + parseInt(start.split(':')[1])
    const endMinutes = parseInt(end.split(':')[0]) * 60 + parseInt(end.split(':')[1])
    
    return currentTime >= startMinutes && currentTime <= endMinutes
  }
  
  // 延迟推送
  delayPush(pushData) {
    const { start } = this.agentConfig.pushPreferences.timeRange
    const startTime = start.split(':')
    const tomorrow = new Date()
    tomorrow.setDate(tomorrow.getDate() + 1)
    tomorrow.setHours(parseInt(startTime[0]), parseInt(startTime[1]), 0, 0)
    
    const delay = tomorrow.getTime() - Date.now()
    
    setTimeout(() => {
      this.executePush(pushData)
    }, delay)
  }
  
  // 触发数字人播报
  triggerDigitalHumanAnnouncement(pushData) {
    const announcementMessage = this.generateAnnouncementMessage(pushData)
    const duration = this.calculateAnnouncementDuration(pushData)
    
    const announcement = {
      id: 'announcement_' + Date.now(),
      message: announcementMessage,
      type: pushData.type,
      urgency: pushData.urgency,
      duration: duration,
      timestamp: Date.now(),
      data: pushData.data
    }
    
    this.announcementQueue.push(announcement)
    this.statistics.announcements += 1
    
    // 发送到数字人组件
    this.emitEvent('digitalHumanAnnouncement', announcement)
    
    console.log('🎙️ 数字人播报:', announcementMessage)
  }
  
  // 生成播报消息
  generateAnnouncementMessage(pushData) {
    const templates = {
      policy_update: [
        `重要政策更新通知：${pushData.data?.title || pushData.content}，建议您关注相关影响。`,
        `检测到新的相关政策：${pushData.data?.title || pushData.content}，匹配度较高，请及时了解详情。`
      ],
      urgent_policy: [
        `紧急政策通知：${pushData.data?.title || pushData.content}，请立即关注！`,
        `高优先级政策提醒：${pushData.data?.title || pushData.content}，建议优先处理。`
      ],
      daily_digest: [
        `今日政策摘要：为您推荐了${pushData.data?.length || 0}项相关政策，请查看详情。`,
        `每日智能推荐已更新，共${pushData.data?.length || 0}项政策值得关注。`
      ],
      welcome_recommendations: [
        `智能推荐系统已为您准备就绪，基于您的企业画像匹配了${pushData.data?.length || 0}项相关政策。`,
        `欢迎使用智能政策助手，已为您个性化推荐${pushData.data?.length || 0}项政策。`
      ]
    }
    
    const typeTemplates = templates[pushData.type] || [`通知：${pushData.content}`]
    return typeTemplates[Math.floor(Math.random() * typeTemplates.length)]
  }
  
  // 计算播报持续时间
  calculateAnnouncementDuration(pushData) {
    const baseTime = 5000 // 基础5秒
    const urgencyMultiplier = pushData.urgency === 'high' ? 1.5 : 1
    const contentLength = (pushData.data?.title || pushData.content || '').length
    const lengthTime = Math.min(contentLength * 100, 5000) // 每字符100ms，最多5秒
    
    return Math.round((baseTime + lengthTime) * urgencyMultiplier)
  }
  
  // 生成定制化推荐
  async generateCustomizedRecommendations(analysis = null) {
    console.log('🎯 生成定制化推荐...')
    
    const profile = this.agentConfig.userProfile
    let recommendations = []
    
    // 如果有分析结果，优先基于分析结果推荐
    if (analysis && analysis.topics && analysis.topics.length > 0) {
      console.log('🎯 基于意图分析生成推荐:', analysis.topics)
      
      // 基于主题获取相关政策
      for (const topic of analysis.topics) {
        if (topic.includes('博士后')) {
          recommendations.push(...await this.getPostdocPolicies())
        } else if (topic.includes('企业')) {
          recommendations.push(...await this.getIndustrySpecificPolicies(profile.industry))
          recommendations.push(...await this.getCompanySizeSpecificPolicies(profile.companySize))
        } else if (topic.includes('税收')) {
          recommendations.push(...await this.getTaxPolicies())
        } else if (topic.includes('补贴')) {
          recommendations.push(...await this.getSubsidyPolicies())
        }
      }
    } else {
      // 基于行业获取政策
      const industryPolicies = await this.getIndustrySpecificPolicies(profile.industry)
      recommendations.push(...industryPolicies)
      
      // 基于企业规模获取政策
      const sizePolicies = await this.getCompanySizeSpecificPolicies(profile.companySize)
      recommendations.push(...sizePolicies)
      
      // 基于地区获取政策
      const locationPolicies = await this.getLocationSpecificPolicies(profile.location)
      recommendations.push(...locationPolicies)
    }
    
    // 去重并排序
    recommendations = this.deduplicateAndRank(recommendations)
    
    // 计算匹配分数
    recommendations.forEach(policy => {
      policy.matchScore = this.calculatePolicyRelevance(policy)
      policy.aiInsights = this.generateAIInsights(policy, profile)
      
      // 如果有分析结果，根据紧急程度调整分数
      if (analysis && analysis.urgency === 'high') {
        policy.matchScore += 0.1
      }
    })
    
    // 按匹配分数排序
    recommendations.sort((a, b) => b.matchScore - a.matchScore)
    
    return recommendations.slice(0, 20) // 返回前20个推荐
  }
  
  // 生成AI洞察
  generateAIInsights(policy, profile) {
    const insights = []
    
    // 收益分析
    if (policy.benefit) {
      insights.push(`预期收益：${policy.benefit}`)
    }
    
    // 适用性分析
    if (policy.industry && policy.industry.includes(profile.industry)) {
      insights.push('高度适用于您的行业')
    }
    
    // 时效性分析
    if (policy.deadline) {
      const daysLeft = Math.ceil((policy.deadline - Date.now()) / (24 * 60 * 60 * 1000))
      if (daysLeft <= 30) {
        insights.push(`申请截止${daysLeft}天，建议尽快处理`)
      }
    }
    
    return insights
  }
  
  // 去重并排序
  deduplicateAndRank(recommendations) {
    const unique = recommendations.filter((policy, index, self) => 
      index === self.findIndex(p => p.id === policy.id)
    )
    
    return unique
  }
  
  // 获取行业特定政策
  async getIndustrySpecificPolicies(industry) {
    const policyDatabase = {
      'ecommerce': [
        {
          id: 'ecom_1',
          title: '跨境电商综合试验区税收优惠',
          type: 'tax_policy',
          industry: ['ecommerce'],
          region: '全国',
          benefit: '增值税减免30%',
          description: '在跨境电商综合试验区开展业务可享受增值税优惠政策',
          requirements: ['在试验区注册', '跨境电商业务'],
          urgency: 'medium',
          icon: 'ShoppingCart',
          matchScore: 0.9
        },
        {
          id: 'ecom_2',
          title: '电商企业物流补贴政策',
          type: 'subsidy_policy',
          industry: ['ecommerce', 'logistics'],
          region: '华东地区',
          benefit: '物流成本补贴20%',
          description: '支持电商企业降低物流成本，提高竞争力',
          requirements: ['电商平台', '年交易额1000万以上'],
          urgency: 'low',
          icon: 'Truck',
          matchScore: 0.8
        }
      ],
      'manufacturing': [
        {
          id: 'manu_1',
          title: '制造业智能化改造补贴',
          type: 'subsidy_policy',
          industry: ['manufacturing'],
          region: '全国',
          benefit: '最高补贴1000万元',
          description: '支持制造业企业进行智能化改造升级',
          requirements: ['制造业企业', '智能化改造项目'],
          urgency: 'high',
          icon: 'Settings',
          matchScore: 0.95
        }
      ],
      'tech': [
        {
          id: 'tech_1',
          title: '高新技术企业税收优惠',
          type: 'tax_policy',
          industry: ['tech'],
          region: '全国',
          benefit: '企业所得税15%',
          description: '高新技术企业享受15%的优惠税率',
          requirements: ['高新技术企业认定', '研发投入占比4%以上'],
          urgency: 'medium',
          icon: 'Zap',
          matchScore: 0.9
        }
      ]
    }
    
    return policyDatabase[industry] || []
  }
  
  // 获取企业规模特定政策
  async getCompanySizeSpecificPolicies(size) {
    const sizePolicies = {
      'small': [
        {
          id: 'small_1',
          title: '小微企业税收减免政策',
          type: 'tax_policy',
          industry: ['all'],
          region: '全国',
          benefit: '年应纳税所得额100万以下减免50%',
          description: '小微企业享受企业所得税优惠政策',
          requirements: ['小微企业标准', '年营业额500万以下'],
          urgency: 'medium',
          icon: 'DollarSign',
          matchScore: 0.85
        }
      ],
      'medium': [
        {
          id: 'medium_1',
          title: '中小企业发展基金支持',
          type: 'fund_policy',
          industry: ['all'],
          region: '全国',
          benefit: '低息贷款支持',
          description: '为中小企业提供发展资金支持',
          requirements: ['中小企业认定', '具有发展潜力'],
          urgency: 'low',
          icon: 'Building',
          matchScore: 0.75
        }
      ],
      'large': [
        {
          id: 'large_1',
          title: '大型企业研发费用加计扣除',
          type: 'tax_policy',
          industry: ['all'],
          region: '全国',
          benefit: '研发费用200%扣除',
          description: '大型企业研发费用可按200%扣除',
          requirements: ['大型企业', '有研发投入'],
          urgency: 'medium',
          icon: 'FileText',
          matchScore: 0.8
        }
      ]
    }
    
    return sizePolicies[size] || []
  }
  
  // 获取博士后政策
  async getPostdocPolicies() {
    return [
      {
        id: 'postdoc_1',
        title: '博士后科学基金资助',
        type: 'funding_policy',
        industry: ['research', 'tech'],
        region: '全国',
        benefit: '每年8-12万元资助',
        description: '为博士后研究人员提供科研资助',
        requirements: ['博士学位', '35岁以下'],
        urgency: 'medium',
        icon: 'GraduationCap',
        matchScore: 0.9
      },
      {
        id: 'postdoc_2',
        title: '博士后生活补贴',
        type: 'subsidy_policy',
        industry: ['research'],
        region: '全国',
        benefit: '每月3000-8000元',
        description: '博士后在站期间生活补贴',
        requirements: ['博士后进站'],
        urgency: 'low',
        icon: 'Home',
        matchScore: 0.85
      }
    ]
  }

  // 获取税收政策
  async getTaxPolicies() {
    return [
      {
        id: 'tax_1',
        title: '高新技术企业税收优惠',
        type: 'tax_policy',
        industry: ['tech'],
        region: '全国',
        benefit: '企业所得税15%',
        description: '高新技术企业享受优惠税率',
        requirements: ['高新技术企业认定'],
        urgency: 'medium',
        icon: 'Calculator',
        matchScore: 0.9
      },
      {
        id: 'tax_2',
        title: '小微企业税收减免',
        type: 'tax_policy',
        industry: ['all'],
        region: '全国',
        benefit: '所得税减免50%',
        description: '小微企业税收优惠政策',
        requirements: ['小微企业标准'],
        urgency: 'medium',
        icon: 'Percent',
        matchScore: 0.85
      }
    ]
  }

  // 获取补贴政策
  async getSubsidyPolicies() {
    return [
      {
        id: 'subsidy_1',
        title: '创新创业补贴',
        type: 'subsidy_policy',
        industry: ['tech', 'startup'],
        region: '全国',
        benefit: '最高50万元补贴',
        description: '支持创新创业项目发展',
        requirements: ['创新项目', '符合产业政策'],
        urgency: 'high',
        icon: 'Lightbulb',
        matchScore: 0.9
      },
      {
        id: 'subsidy_2',
        title: '数字化转型补贴',
        type: 'subsidy_policy',
        industry: ['manufacturing', 'ecommerce'],
        region: '全国',
        benefit: '最高500万元补贴',
        description: '企业数字化转型专项补贴',
        requirements: ['数字化改造项目'],
        urgency: 'medium',
        icon: 'Smartphone',
        matchScore: 0.8
      }
    ]
  }

  // 获取地区特定政策
  async getLocationSpecificPolicies(location) {
    // 简化实现，返回地区相关政策
    return [
      {
        id: 'region_1',
        title: `${location}区域发展优惠政策`,
        type: 'regional_policy',
        industry: ['all'],
        region: location,
        benefit: '多项优惠措施',
        description: `${location}为促进区域发展推出的综合优惠政策`,
        requirements: ['在该区域经营'],
        urgency: 'low',
        icon: 'MapPin',
        matchScore: 0.7
      }
    ]
  }
  
  // 事件监听器管理
  addEventListener(event, callback) {
    if (!this.eventListeners.has(event)) {
      this.eventListeners.set(event, [])
    }
    this.eventListeners.get(event).push(callback)
  }
  
  removeEventListener(event, callback) {
    if (this.eventListeners.has(event)) {
      const callbacks = this.eventListeners.get(event)
      const index = callbacks.indexOf(callback)
      if (index > -1) {
        callbacks.splice(index, 1)
      }
    }
  }
  
  emitEvent(event, data) {
    if (this.eventListeners.has(event)) {
      this.eventListeners.get(event).forEach(callback => {
        try {
          callback(data)
        } catch (error) {
          console.error(`事件处理器错误 (${event}):`, error)
        }
      })
    }
  }
  
  // 发送欢迎消息
  sendWelcomeMessage() {
    setTimeout(() => {
      this.queueNormalPush({
        type: 'welcome',
        title: '智能Agent助手已启动',
        content: '我将为您提供个性化的政策推送和智能分析服务',
        urgency: 'low',
        enableDigitalHuman: true
      })
    }, 3000)
  }
  
  // 安排每日摘要
  scheduleDailyDigest() {
    const scheduleNext = () => {
      const now = new Date()
      const next = new Date(now)
      next.setDate(next.getDate() + 1)
      next.setHours(9, 0, 0, 0) // 每天上午9点
      
      const delay = next.getTime() - now.getTime()
      
      setTimeout(() => {
        this.generateDailyDigest()
        scheduleNext() // 递归安排下一次
      }, delay)
    }
    
    scheduleNext()
  }
  
  // 生成每日摘要
  async generateDailyDigest() {
    console.log('📋 生成每日摘要...')
    
    const recommendations = await this.generateCustomizedRecommendations()
    const highPriorityPolicies = recommendations.filter(p => p.urgency === 'high')
    
    this.queueNormalPush({
      type: 'daily_digest',
      title: '每日政策摘要',
      content: `今日为您推荐${recommendations.length}项政策，其中${highPriorityPolicies.length}项为高优先级`,
      data: recommendations.slice(0, 10),
      urgency: 'medium',
      enableDigitalHuman: true
    })
  }
  
  // 安排周报
  scheduleWeeklyReport() {
    // 简化实现，每周一生成周报
    const scheduleNext = () => {
      const now = new Date()
      const next = new Date(now)
      const daysUntilMonday = (1 + 7 - now.getDay()) % 7 || 7
      next.setDate(next.getDate() + daysUntilMonday)
      next.setHours(10, 0, 0, 0)
      
      const delay = next.getTime() - now.getTime()
      
      setTimeout(() => {
        this.generateWeeklyReport()
        scheduleNext()
      }, delay)
    }
    
    scheduleNext()
  }
  
  // 生成周报
  generateWeeklyReport() {
    console.log('📊 生成周报...')
    
    this.queueNormalPush({
      type: 'weekly_report',
      title: '每周政策分析报告',
      content: '本周政策动态总结和下周重点关注事项',
      data: {
        totalPolicies: this.statistics.policyMatches,
        highPriorityCount: this.statistics.highPriorityPushes,
        recommendations: 'trend_analysis'
      },
      urgency: 'low',
      enableDigitalHuman: false
    })
  }
  
  // 安排重要提醒
  scheduleImportantReminders() {
    // 每小时检查一次重要提醒
    setInterval(() => {
      this.checkImportantReminders()
    }, 3600000)
  }
  
  // 检查重要提醒
  async checkImportantReminders() {
    // 检查即将到期的政策申请
    const upcomingDeadlines = await this.getUpcomingDeadlines()
    
    for (const deadline of upcomingDeadlines) {
      this.queueHighPriorityPush({
        type: 'deadline_reminder',
        title: '政策申请截止提醒',
        content: `${deadline.title} 将在${deadline.daysLeft}天后截止申请`,
        data: deadline,
        urgency: deadline.daysLeft <= 3 ? 'high' : 'medium',
        enableDigitalHuman: deadline.daysLeft <= 7
      })
    }
  }
  
  // 获取即将到期的政策
  async getUpcomingDeadlines() {
    // 模拟获取即将到期的政策
    const now = Date.now()
    const policies = await this.generateCustomizedRecommendations()
    
    return policies
      .filter(policy => policy.deadline && policy.deadline > now)
      .map(policy => ({
        ...policy,
        daysLeft: Math.ceil((policy.deadline - now) / (24 * 60 * 60 * 1000))
      }))
      .filter(policy => policy.daysLeft <= 30)
      .sort((a, b) => a.daysLeft - b.daysLeft)
  }
  
  // 安排用户画像更新
  scheduleProfileUpdate() {
    // 每周更新一次用户画像
    setInterval(() => {
      this.updateUserProfileAnalysis()
    }, 7 * 24 * 60 * 60 * 1000)
  }
  
  // 更新用户画像分析
  updateUserProfileAnalysis() {
    console.log('👤 更新用户画像分析...')
    
    // 基于用户行为更新画像
    if (this.statistics.userEngagement > 50) {
      this.agentConfig.userProfile.riskLevel = 'high'
    } else if (this.statistics.userEngagement > 20) {
      this.agentConfig.userProfile.riskLevel = 'medium'
    } else {
      this.agentConfig.userProfile.riskLevel = 'low'
    }
    
    this.saveUserProfile()
    this.emitEvent('profileUpdated', this.agentConfig.userProfile)
  }
  
  // 重新分析和推荐
  async reanalyzeAndRecommend() {
    console.log('🔄 重新分析和推荐...')
    
    const newRecommendations = await this.generateCustomizedRecommendations()
    
    if (newRecommendations.length > 0) {
      this.queueNormalPush({
        type: 'updated_recommendations',
        title: '推荐已更新',
        content: `基于您的最新偏好，更新了${newRecommendations.length}项政策推荐`,
        data: newRecommendations.slice(0, 5),
        urgency: 'medium',
        enableDigitalHuman: true
      })
    }
  }
  
  // 检查市场变化
  checkMarketChanges() {
    // 简化的市场变化检查
    if (Math.random() > 0.9) {
      this.queueNormalPush({
        type: 'market_change',
        title: '市场变化提醒',
        content: '检测到相关市场环境变化，可能影响政策适用性',
        urgency: 'low',
        enableDigitalHuman: false
      })
    }
  }
  
  // 检查风险变化
  checkRiskChanges() {
    // 简化的风险变化检查
    if (Math.random() > 0.95) {
      this.queueHighPriorityPush({
        type: 'risk_alert',
        title: '风险提醒',
        content: '检测到潜在政策风险，建议关注相关动态',
        urgency: 'high',
        enableDigitalHuman: true
      })
    }
  }
  
  // 获取统计信息
  getStatistics() {
    return {
      ...this.statistics,
      isActive: this.isActive,
      queueLength: this.pushQueue.length,
      announcementQueue: this.announcementQueue.length,
      lastUpdateTime: this.lastUpdateTime,
      userProfile: this.agentConfig.userProfile
    }
  }
  
  // 获取推送队列状态
  getPushQueueStatus() {
    return {
      total: this.pushQueue.length,
      high: this.pushQueue.filter(p => p.priority === 'high').length,
      medium: this.pushQueue.filter(p => p.urgency === 'medium').length,
      low: this.pushQueue.filter(p => p.urgency === 'low').length,
      processed: this.pushQueue.filter(p => p.processed).length
    }
  }
  
  // 分析用户意图
  async analyzeUserIntent(userInput) {
    console.log('🧠 分析用户意图:', userInput)
    
    // 简化的意图分析
    const intent = {
      intent: '政策咨询',
      confidence: 0.85,
      topics: [],
      needsRecommendation: false,
      urgency: 'normal',
      relatedPolicies: [],
      estimatedTime: '15-30个工作日',
      successRate: 0.8
    }
    
    const inputLower = userInput.toLowerCase()
    
    // 分析主题
    if (inputLower.includes('博士后') || inputLower.includes('博士')) {
      intent.topics.push('博士后政策')
      intent.needsRecommendation = true
    }
    if (inputLower.includes('企业') || inputLower.includes('公司')) {
      intent.topics.push('企业优惠')
      intent.needsRecommendation = true
    }
    if (inputLower.includes('税收') || inputLower.includes('税务')) {
      intent.topics.push('税收政策')
      intent.needsRecommendation = true
    }
    if (inputLower.includes('补贴') || inputLower.includes('资助')) {
      intent.topics.push('财政补贴')
      intent.needsRecommendation = true
    }
    
    // 分析紧急程度
    if (inputLower.includes('紧急') || inputLower.includes('急需') || inputLower.includes('截止')) {
      intent.urgency = 'high'
    } else if (inputLower.includes('尽快') || inputLower.includes('优先')) {
      intent.urgency = 'medium'
    }
    
    // 默认主题
    if (intent.topics.length === 0) {
      intent.topics.push('通用政策')
    }
    
    return intent
  }

  // 销毁代理
  destroy() {
    this.stop()
  }

  // 停止代理
  stop() {
    console.log('🛑 智能Agent代理停止中...')
    this.isActive = false
    this.pushQueue = []
    this.announcementQueue = []
    this.eventListeners.clear()
    console.log('✅ 智能Agent代理已停止')
  }
}

// 导出类和默认单例
export { IntelligentAgent }

// 创建全局单例
const intelligentAgent = new IntelligentAgent()

export default intelligentAgent 